<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form pt-[15px]" v-if="premsStore.isEditActivitySetting">
      <el-button type="primary" @click="handleOpen()">新增优惠活动</el-button>
    </div>
    <div class="py-[15px] flex justify-start">
      <el-alert title="拖动广告可调动广告排序" type="warning" show-icon :closable="false" />
    </div>
    <div class="grow-[1] h-0">
      <el-table
        scrollbar-always-on
        v-loading="state.loading"
        :data="list"
        height="100%"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column align="center" prop="Sort" label="序号" width="60" />
        <el-table-column align="center" prop="Name" label="活动名称" />
        <el-table-column align="center" prop="Note" label="广告图片" width="330">
          <template #default="{ row }: TableItem">
            <div
              class="mx-auto w-[300px] h-[100px] bg-[#f5f7fa] flex justify-center items-center rounded-[8px] overflow-hidden"
            >
              <template v-if="!row.ActivityImg">--</template>
              <ImgPreviewDialog :src="row.ActivityImg" v-else>
                <el-image class="!w-full !h-full" :src="netPath(row.ActivityImg)" fit="cover" />
              </ImgPreviewDialog>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Note" label="内容图片" width="330">
          <template #default="{ row }: TableItem">
            <div
              class="mx-auto w-[300px] h-[100px] bg-[#f5f7fa] flex justify-center items-center rounded-[8px] overflow-hidden"
            >
              <template v-if="!row.ContentImg">--</template>
              <ImgPreviewDialog :src="row.ContentImg" v-else>
                <el-image class="!w-full !h-full" :src="netPath(row.ContentImg)" fit="cover" />
              </ImgPreviewDialog>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Device" label="活动状态">
          <template #default="{ row }: TableItem">
            <el-dropdown placement="bottom" @command="(e: number) => handleChangeStatus(row, e)">
              <el-button v-if="row.Status == 1" type="success" size="small">开启</el-button>
              <el-button v-else type="danger" size="small">关闭</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="row.Status == 1" :command="1">
                    开启
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.Status == 0" :command="0">
                    关闭
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="170">
          <template #default="{ row }: TableItem">
            <el-button
              v-if="premsStore.isEditActivitySetting"
              type="primary"
              size="small"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="premsStore.isEditActivitySetting && row.Type != 1"
              type="danger"
              size="small"
              @click="handleDel(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <EditDiscountDialog
      ref="editDiscountDialogRef"
      :type="type"
      :data="curData"
      @update="getData"
    />
    <TurntableDiscountDialog ref="turntableDiscountDialogRef" :data="curData" @update="getData" />
  </div>
</template>
<script setup lang="ts">
import EditDiscountDialog from "./edit-discount-dialog.vue";
import TurntableDiscountDialog from "./turntable-discount-dialog.vue";
import ImgPreviewDialog from "@/components/img-preview-dialog.vue";
import { useList } from "@/hooks/useList";
import {
  reqActivityDiscountDel,
  reqActivityDiscountEdit,
  reqActivityDiscountList
} from "@/api/activity";
import { netPath } from "@/utils/common";
import { message } from "@/utils/message";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: ActivityDiscountMo;
}
const premsStore = usePremsStore();
const editDiscountDialogRef = ref();
const turntableDiscountDialogRef = ref();

const type = ref<"add" | "edit">("add");
const curData = ref<ActivityDiscountMo | null>(null);
const { state, list, getData, search } = useList<ActivityDiscountMo, {}>(
  reqActivityDiscountList,
  () => ({})
);

const handleChangeStatus = async (item: ActivityDiscountMo, key: number) => {
  if (!premsStore.isEditActivitySetting) return;
  try {
    state.loading = true;
    await reqActivityDiscountEdit({
      ...item,
      Status: key
    });
    message.success("修改状态成功");
    state.loading = false;
    item.Status = key;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const handleOpen = () => {
  type.value = "add";
  nextTick(() => {
    editDiscountDialogRef.value?.open();
  });
};

const handleEdit = (item: ActivityDiscountMo) => {
  type.value = "edit";
  curData.value = item;
  if (item.Type == 0) {
    nextTick(() => {
      editDiscountDialogRef.value?.open();
    });
  } else {
    nextTick(() => {
      turntableDiscountDialogRef.value?.open();
    });
  }
};
const handleDel = (item: ActivityDiscountMo) => {
  ElMessageBox.confirm(`是否进行【删除】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqActivityDiscountDel({
            Id: item.Id
          });
          message.success("删除成功");
          getData();
          done(); // 操作成功后关闭对话框
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

onMounted(() => {
  getData();
});
defineExpose({
  getData() {
    search();
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-table__row) {
  cursor: pointer;
}
</style>
